from PySide6.QtWidgets import QDialog,QMessageBox

from views.salary.model.salary import SalaryScale
from views.salary.salaryscale.operationsalaryscale import Ui_salaryscaleDialog
from views.person.model.person import PersonBaseInfo
from PySide6.QtCore import QDate
import datetime
from sqlalchemy.orm import Session
from settings.publicvar import engine

class OperationSalaryScale(QDialog,Ui_salaryscaleDialog):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_state(is_state)
        self.setFormStructure(data)
        self.changebtn.clicked.connect(self.changeItem)
        self.resetbtn.clicked.connect(self.resetItem)
        self.addbtn.clicked.connect(self.addItem)
        self.name.editingFinished.connect(self.nameFinishedFun)
        self.deletebtn.clicked.connect(self.deleteItem)


    def if_state(self,is_state):
        if is_state=='add':
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('请输入身份证号！')
            self.changebtn.hide()
            self.deletebtn.hide()
        elif is_state == 'change':
            self.addbtn.hide()
            self.titlelabel.setText('修改岗位信息')
            self.name.setDisabled(True)
            self.deletebtn.hide()
        elif is_state == 'view':
            self.name.setDisabled(True)
            self.titlelabel.setText('查看岗位信息')
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
            self.deletebtn.hide()
        else:
            self.name.setDisabled(True)
            self.titlelabel.setText('删除岗位信息')
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()

    def setFormStructure(self, data):
        if data != '':
            self.idx.setText(str(data[0]))
            self.name.setText(data[1])
            self.salaryscale_level.setText(data[2])
            date = QDate.fromString(data[3], "yyyy-MM-dd")
            if date.isValid():
                self.salaryscale_date.setDate(date)
            else:
                self.salaryscale_date.setDate(QDate(1, 1, 1))
                self.salaryscale_date.setSpecialValueText("请选择日期")
            self.salaryscale_type.setText(data[4])
            self.mark.setText(data[5])

    def changeItem(self):
        data = self.get_form_data()
        if data:
            with Session(engine) as session, session.begin():
                salaryscale = session.query(SalaryScale).filter(SalaryScale.id == data[0])
                salaryscale.update(data[1])
            self.close()

    def resetItem(self):
        self.salaryscale_type.setText('')
        self.salaryscale_level.setText('')
        self.salaryscale_type.setText('')
        self.salaryscale_date.setDate(QDate(1,1,1))
        self.salaryscale_date.setSpecialValueText("请选择日期")
        self.mark.setText('')

    def addItem(self):
        data = self.get_form_data()
        if data:
            with Session(engine) as session, session.begin():
                data[1]['name_id'] = self.name_id
                salaryscale = SalaryScale(**data[1])
                session.add(salaryscale)
            self.close()

    def deleteItem(self):
        data = self.get_form_data()
        with Session(engine) as session, session.begin():
            session.query(SalaryScale).filter(SalaryScale.id == data[0]).delete()
            self.close()
            QMessageBox.critical(None,'删除成功','数据删除成功')

# 获取表单数据
    def get_form_data(self):
        idx = self.idx.text()
        salaryscale_level = self.salaryscale_level.text()
        salaryscale_date= self.salaryscale_date.date()
        salaryscale_date = datetime.date(salaryscale_date.year(),salaryscale_date.month(),salaryscale_date.day())
        salaryscale_type = self.salaryscale_type.text()
        mark = self.mark.text()
        if salaryscale_level == '' or salaryscale_type == '' :
            data = False
            QMessageBox.critical(None,"数据为空","你填写的数据不能为空！")
        else:
            data = (idx, {'salaryscale_level': salaryscale_level, 'salaryscale_date': salaryscale_date,
                      'salaryscale_type': salaryscale_type, 'mark': mark,})
        return data

    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session, session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                self.name.setText(personbase.name)
                self.name_id = personbase.id
            except:
                QMessageBox.critical(None, '失败', '没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')